<template>
  <div class="app-container" v-loading="loading">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="扫码器" prop="bcr">
        <el-input
          v-model="queryParams.bcr"
          placeholder="请输入扫码器"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="查询时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 350px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        <el-button  size="mini" @click="detailIsOpen">数据列表</el-button>
      </el-form-item>
    </el-form>







    <div id="main" style="width: 1300px;height:600px; margin:auto;"></div>

    <!-- 详情界面 -->
    <el-dialog  :title="detailTitle" :visible.sync="detailOpen" width="1000px" append-to-body>

      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            :loading="exportLoading"
            @click="handleExport"
            v-hasPermi="['wcs:bcr_percent:export']"
          >导出</el-button>
        </el-col>
<!--        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
      </el-row>
      <el-table v-loading="loading" :data="bcr_percentList" @selection-change="handleSelectionChange">
        <!--      <el-table-column type="selection" width="55" align="center" />-->
        <!--      <el-table-column label="id" align="center" prop="id" />-->
        <el-table-column label="扫码器" align="center" prop="bcr" />
        <el-table-column label="总数" align="center" prop="total" />
        <el-table-column label="noread" align="center" prop="noread" />
        <!--      <el-table-column label="000" align="center" prop="bar000" />-->
        <!--      <el-table-column label="777" align="center" prop="bar777" />-->
        <!--      <el-table-column label="空" align="center" prop="barEmpty" />-->
        <el-table-column label="扫码成功" align="center" prop="barSuccess" />
        <el-table-column label="扫码成功率" align="center" prop="successPercent" />
        <!--      <el-table-column label="000比率" align="center" prop="bar000Percent" />-->
        <!--      <el-table-column label="777比率" align="center" prop="bar777Percent" />-->
        <!--      <el-table-column label="空比率" align="center" prop="barEmptyPercent" />-->

      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-dialog>
  </div>

</template>

<script>
import { listBcr_percent, getBcr_percent, delBcr_percent, addBcr_percent, updateBcr_percent, exportBcr_percent } from "@/api/wcs/bcr_percent";
import {initRangeDate} from "@/api/wcs/general/wcs_tool.js";
import  echarts from 'echarts';

export default {
  name: "Bcr_percent",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 扫码率表格数据
      bcr_percentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        bcr: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      detailTitle:"",
      detailOpen:false,
      echarsData:[],
      legendData:[]
    };
  },
  created() {
    // this.setCurrentDate();
    this.dateRange = initRangeDate();
    this.getList();
    // this.initChar();
  },
  methods: {
    /** 查询扫码率列表 */
    getList() {
      this.loading = true;
      // console.log(Date.parse(new Date()))
      let startLogTime = Date.parse(new Date());
      listBcr_percent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        // console.log(Date.parse(new Date()))

        this.bcr_percentList = response.rows;
        this.total = response.total;
        this.loading = false;


        let bcrData = [];
        let percentData = [];
        this.bcr_percentList.forEach(data =>{
          //获取bcr添加到数组
          bcrData.push(data.bcr);
          //取出数据中的%并将字符串转化为数字
          // let successPercentNumber = Number(data.successPercent.replaceAll('%',''));
          let successPercentNumber = Number(data.successPercent.replace('%',''));
          //获取百分比添加到数组
          percentData.push(successPercentNumber);
        });
        this.echarsData = percentData;
        this.legendData = bcrData;
        // console.log(this.bcr_percentList.length);

        if(this.bcr_percentList.length == 0){
          this.$message('无数据');
        }
        //初始化echar图表
        this.initChar(bcrData,percentData);
        console.log('耗时：'+(Date.parse(new Date())-startLogTime)/1000+'s!')
        // console.log(Date.parse(new Date()))
      });

    },
    // /**
    //  * 通过bcr得到该bcr下的所有数据
    //  *
    //  * */
    // getOneDataByBcr(bcr){
    //   let dateByBcr = {};
    //   this.bcr_percentList.forEach(data =>{
    //     if(data.bcr===bcr){
    //       // console.log(data)
    //       dateByBcr = data;
    //     }
    //   });
    //   return dateByBcr;
    // },

    /**
     * 初始化echars
     */
    initChar(bcrData,percentData) {
      // 基于准备好的dom，初始化echarts实例
      var myChart = echarts.init(document.getElementById('main'));

      // 指定图表的配置项和数据
      var option = {
        title: {
          text: '扫码率'
        },
        tooltip: {
          formatter: '扫码器：{b} <br> 读码率：{c}%'
        },
        //工具框
        toolbox: {
          //悬停在小图标的文本提示
          showTitle:true,
          //工具种类
          feature: {
            //数据视图
            dataView: {
              show: false,
              //只读设置
              readOnly: true,  lang:['','关闭'],
              //小图标的文本提示，配合showTitle使用
              title:"数据视图",
            },
            //重置
            restore: {show: true},
            //图片下载
            saveAsImage: {show: true},

          }
        },
        legend: {
          data: ['读码率']
        },
        xAxis: {
          // data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
          data: bcrData,
          name:'扫码器',				    //---轴名称
          position:"bottom",
          nameTextStyle:{				//---坐标轴名称样式
            color:"black",
            padding:[30,0,0,-10],	//---坐标轴名称相对位置
            fontWeight:"bold" //坐标轴名称字体粗细
          },
          axisLabel: {
            show: true,
            interval: 'auto',
            formatter: '{value}',
          },

        },
        yAxis: {
          type: 'value',
          axisLabel: {
            show: true,
            interval: 'auto',
            formatter: '{value}%',
          },
          show: true,
          position:'left',			//---y轴位置
          offset:0,					//---y轴相对于默认位置的偏移
          name:'百分比',				    //---轴名称
          nameLocation:'end',			//---轴名称相对位置value
          nameTextStyle:{				//---坐标轴名称样式
            color:"black",
            padding:[20,50,0,0],	//---坐标轴名称相对位置
            fontWeight:"bold" //坐标轴名称字体粗细
          },
          nameGap:15,					//---坐标轴名称与轴线之间的距离
          nameRotate:0,			//---坐标轴名字旋转
        }  ,
        series: [
          {
            name: '读码率',
            type: 'bar',
            // data: [5, 20, 36, 10, 10.55, 20,98.99],
            data: percentData,
            itemStyle: {
              normal: {
                label: {
                  show: true,  //开启显示
                  position: 'top',  //在上方显示
                  textStyle: {//数值样式
                    color: 'black', //柱图显示字体颜色
                    fontSize: 14    //柱图显示字体大小
                  },
                  formatter: '{c}%'
                }
              }
            },
            barWidth : 30, //柱图宽度
          }
        ]
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
    /**
    * 将当天时间设置
    * */
    setCurrentDate(){
      this.dateRange = initRangeDate();
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        bcr: null,
        total: null,
        noread: null,
        notNoread: null,
        successPercent: null,
        creatime: null,
        modifytime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 搜索按钮操作 */
    detailIsOpen() {
      this.detailOpen = true;
      this.detailTitle = "扫码率详情";
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = initRangeDate();
      // this.setCurrentDate();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加扫码率";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBcr_percent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改扫码率";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateBcr_percent(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBcr_percent(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除扫码率编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delBcr_percent(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有扫码率数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportBcr_percent(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        })
    }
  }
};
</script>
